package com.lin.fengxiu.service;

import com.lin.fengxiu.bo.OrderMessageBO;
import com.lin.fengxiu.core.enumeration.OrderStatus;
import com.lin.fengxiu.exception.http.ServerErrorException;
import com.lin.fengxiu.model.Order;
import com.lin.fengxiu.repository.OrderRepository;
import com.lin.fengxiu.repository.UserCouponRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.html.Option;
import java.util.Optional;

/**
 * @ClassName CouponBackService
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/4/14 6:28
 * @Version 1.0
 */
@Service
public class CouponBackService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserCouponRepository userCouponRepository;

    @Transactional
    public void returnBack(OrderMessageBO bo){
        Long couponId = bo.getCouponId();
        Long uid = bo.getUserId();
        Long oid = bo.getOrderId();

        // 优惠券不为空
        if(couponId == -1){
            return ;
        }

        // 订单不为空
        Optional<Order> optional = orderRepository.findFirstByUserIdAndId(uid,oid);
        Order order = null;

        try {
            order = optional.orElseThrow(()->{
                throw new ServerErrorException(9999);
            });
        }catch (Throwable e){
            e.printStackTrace();
        }

        // 默认是UNPAID状态做归还；考虑乱序问题，如果先进行订单归还，则为Cancel
        if(order.getStatusEnum().equals(OrderStatus.UNPAID)
                || order.getStatusEnum().equals(OrderStatus.CANCELED)){
            //
            this.userCouponRepository.returnBack(couponId,uid);
        }
    }
}
